package com.yoda.quartzdemo.controller;


import com.github.pagehelper.PageInfo;
import com.yoda.quartzdemo.entity.JobAndTrigger;
import com.yoda.quartzdemo.service.JobService;
import com.yoda.quartzdemo.util.QuartzUtil;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping(value="/job")
public class JobController 
{

	//加入Qulifier注解，通过名称注入bean
	@Resource
	@Qualifier("scheduler")
	private Scheduler scheduler;

	@Resource
    private JobService jobService;
	private static Logger log = LoggerFactory.getLogger(JobController.class);
	

	@PostMapping(value="/addjob")
	public void addjob(@RequestParam(value="jobClassName")String jobClassName,
			@RequestParam(value="jobGroupName")String jobGroupName,
			@RequestParam(value="cronExpression")String cronExpression) throws Exception
	{
		QuartzUtil.addJob(scheduler,jobClassName, jobGroupName, cronExpression);
	}
	



	@PostMapping(value="/pausejob")
	public void pausejob(@RequestParam(value="jobClassName")String jobClassName, @RequestParam(value="jobGroupName")String jobGroupName) throws Exception
	{			
		QuartzUtil.pauseJob(scheduler,jobClassName, jobGroupName);
	}


	@PostMapping(value="/resumejob")
	public void resumejob(@RequestParam(value="jobClassName")String jobClassName, @RequestParam(value="jobGroupName")String jobGroupName) throws Exception
	{			
		QuartzUtil.resumJob(scheduler,jobClassName, jobGroupName);
	}

	
	@PostMapping(value="/reschedulejob")
	public void rescheduleJob(@RequestParam(value="jobClassName")String jobClassName,
			@RequestParam(value="jobGroupName")String jobGroupName,
			@RequestParam(value="cronExpression")String cronExpression) throws Exception
	{			
		QuartzUtil.updateJob(scheduler,jobClassName, jobGroupName, cronExpression);
	}
	

	
	@PostMapping(value="/deletejob")
	public void deletejob(@RequestParam(value="jobClassName")String jobClassName, @RequestParam(value="jobGroupName")String jobGroupName) throws Exception
	{			
		QuartzUtil.deleteJob(scheduler,jobClassName, jobGroupName);
	}
	
    @GetMapping(value="/queryjob")
    @ResponseBody
    public Map<String,Object> queryJob(int pageNum,int pageSize){
        System.out.println(pageNum);
        System.out.println(pageSize);
        PageInfo<JobAndTrigger> jobAndTrigger = jobService.getJobAndTriggerDetails(pageNum, pageSize);
		Map<String, Object> map = new HashMap<>();
		map.put("JobAndTrigger", jobAndTrigger);
		map.put("number", jobAndTrigger.getTotal());
		return map;
    }
	
	
}
